import { createI18n, useI18n, type I18n } from "vue-i18n"

import { useColorMode, useCycleList } from '@vueuse/core'

import { useAppStore } from '@/stores/modules/global'

function getI18n() {
  const modules = import.meta.glob('./i18n/*.js', { eager: true })
  const entries = Object.entries(modules).map(([key, value]: any) => {
    const matched = key.match(/([A-Za-z0-9-_]+)\./i)[1];
    return [matched, value.default];
  })
  // Object.fromEntries()方法是Object.entries()的逆操作，用于将一个键值对数组转为对象。
  const fromEntries = Object.fromEntries(entries)
  return fromEntries
}
const i18nInfo = getI18n()

const lang = localStorage.getItem('language') ?? 'zh-cn'

export const i18n: I18n = createI18n<false>({
  legacy: false,  // you must set `false`, to use Composition API
  locale: lang,
  globalInjection: true, // 全局注册$t方法
  messages: i18nInfo
})

export function useI18nLanguage(): {
  changeTitle: (meta: { title: string }) => void;
  setI18nLanguage: (lang: string) => void
} {
  const { t, locale } = useI18n()
  const appStore = useAppStore()

  function setI18nLanguage(lang: string) {
    locale.value = lang
    appStore.setStoreLocale(lang)
  }

  function changeTitle(meta: { title: string; }) {
    document.title = `${t(meta.title)} | algate-admin`
  }

  return {
    setI18nLanguage,
    changeTitle
  }
}

const mode: any = useColorMode({
  emitAuto: true,
  modes: {
    gray: 'gray',
    cafe: 'cafe'
  }
})

const { state, next } = useCycleList([
  'dark',
  'light',
  'gray',
  'cafe'
])

export const toggleDark = () => {
  const appStore = useAppStore()
  next()
  mode.value = state.value
  appStore.setMode(state.value)
}

